from ryu.base import app_manager
from ryu.controller import ofp_event
from ryu.controller.handler import CONFIG_DISPATCHER, MAIN_DISPATCHER
from ryu.controller.handler import set_ev_cls
from ryu.ofproto import ofproto_v1_3
from ryu.lib.packet import packet
from ryu.lib.packet import ethernet
from ryu.lib.packet import vlan
from ryu.lib.packet import ether_types

import util
topo = util.load_src("topo_query", "topo/topo_query.py").TopoQuery("topo/topo3.json")

class Tracer(app_manager.RyuApp):
	OFP_VERSIONS = [ofproto_v1_3.OFP_VERSION]

	def __init__(self, *args, **kwargs):
		super(Tracer, self).__init__(*args, **kwargs)

	@set_ev_cls(ofp_event.EventOFPSwitchFeatures, CONFIG_DISPATCHER)
	def switch_features_handler(self, ev):
		datapath = ev.msg.datapath

		self.logger.info("switch %s connected to tracer", datapath.id)

	@set_ev_cls(ofp_event.EventOFPPacketIn, MAIN_DISPATCHER)
	def _packet_in_handler(self, ev):
		# If you hit this you might want to increase
		# the "miss_send_length" of your switch
		if ev.msg.msg_len < ev.msg.total_len:
			self.logger.debug("packet truncated: only %s of %s bytes",
                              ev.msg.msg_len, ev.msg.total_len)
		msg = ev.msg
		datapath = msg.datapath
		dpid = datapath.id
		ofproto = datapath.ofproto
		parser = datapath.ofproto_parser
		in_port = msg.match['in_port']

		pkt = packet.Packet(msg.data)
		eth = pkt.get_protocols(ethernet.ethernet)[0]

		if eth.ethertype == ether_types.ETH_TYPE_LLDP:
			# ignore lldp packet
			return
		dst = eth.dst
		src = eth.src

		# vlan test
		vls = pkt.get_protocols(vlan.vlan)
		#vids = map(lambda e: e.vid, vls)
		has_vid = len(vls) > 0
		if has_vid:
			vids = vls[0].vid
			vid1 = (vids & 0xfc0) >> 6
			vid2 = vids & 0x3f
			self.logger.info("packet in [%s:%s] %s --> %s", dpid, in_port, src, dst)
			srcid = int(topo.get_host_link_id(src))
			dstid = int(topo.get_host_link_id(dst))
			links = [x for x in [srcid, vid1, vid2, dstid] if x > 0]
			self.logger.info("\033[32mlinks:\033[0m %s", links)
			path = []
			for i in range(len(links) - 1):
				path.append(links[i])
				path = path + topo.get_path(str(links[i]), str(links[i+1]))
			path.append(dstid)
			self.logger.info("\033[32mpath:\033[0m %s", path)

